﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace PhoneNumber.Classes
{
    internal class MessageSender
    {
        #region windows进程通信机制，包含函数StartSendMessage

        private const int WM_COPYDATA = 0x004A; // 自定义消息

        [DllImport("User32.dll", EntryPoint = "FindWindow")]
        private static extern IntPtr FindWindow(
            string lpClassName,
            string lpWindowName);

        [DllImport("User32.dll", EntryPoint = "SendMessage")]
        private static extern IntPtr SendMessage(
            IntPtr hWnd,
            uint Msg,
            IntPtr wParam,
            ref COPYDATASTRUCT lParam);

        public void StartSendMessage(string form, string message)
        {
            IntPtr window = FindWindow(null, form);
            if (window != IntPtr.Zero)
            {
                byte[] arr = Encoding.Default.GetBytes(message);
                int len = arr.Length;

                COPYDATASTRUCT msg = new COPYDATASTRUCT();
                msg.dwData = IntPtr.Zero;
                msg.cbData = len + 1;     //传递的字节长度
                msg.lpData = Marshal.StringToHGlobalAnsi(message);//将消息存储到非托管内存（返回一个地址

                SendMessage(window, WM_COPYDATA, IntPtr.Zero, ref msg); // 发送消息

                Marshal.FreeHGlobal(msg.lpData); // 释放非托管内存
            }
        }
        #endregion
    }
}
